﻿
@page "/"
@rendermode @(new InteractiveServerRenderMode(prerender: true))

@using Markdig
@using StrategyReportViewer.Data
@inject StrategyReportService ReportService
@inject IJSRuntime JSRuntime

<PageTitle>期货策略报告</PageTitle>

<div class="report-viewer-container @(_selectedReport != null ? "content-visible" : "")">

    <!-- 左侧列表 -->
    <div class="report-list-pane">
        <h4 class="px-3 pt-3">AI策略报告列表</h4>
        <ul class="list-group list-group-flush">
            @foreach (var report in _reports)
            {
                <li class="list-group-item list-group-item-action @((_selectedReport != null && report.Date == _selectedReport.Date && report.Pzdm == _selectedReport.Pzdm) ? "active" : "")"
                    @onclick="() => SelectReport(report)">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">@report.Title</h6>
                        <small>@report.Date</small> <!-- 直接使用Date字符串 -->
                    </div>
                </li>
            }
        </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="report-content-pane">
        @if (_selectedReport != null)
        {
            <!-- 移动端返回按钮 -->
            <button class="btn btn-secondary d-lg-none mb-3" @onclick="ShowList">
                ← 返回列表
            </button>

            @* <h2 class="mb-3">@_selectedReport.Title</h2>
            <div class="text-muted mb-4">
                报告日期: @_selectedReport.Date
            </div> *@

            <div class="markdown-body">
                @((MarkupString)_htmlContent)
            </div>
        }
        else
        {
            <div class="d-flex align-items-center justify-content-center h-100 text-muted">
                <p>请从左侧选择一份报告进行查看</p>
            </div>
        }
    </div>

</div>

@code {
    private List<StrategyReport> _reports = [];
    private StrategyReport? _selectedReport;
    private string _htmlContent = "";

    protected override async Task OnInitializedAsync()
    {
        _reports = await ReportService.GetReportsAsync();
        // 默认选中第一条
        if (_reports.Any())
        {
            await SelectReport(_reports.First());
        }
    }

    private async Task SelectReport(StrategyReport report)
    {
        _selectedReport = report;
        // 使用 Markdig 将 Markdown 转换为 HTML
        _htmlContent = Markdig.Markdown.ToHtml(_selectedReport.Content, new Markdig.MarkdownPipelineBuilder().UseAdvancedExtensions().Build());
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // 当组件渲染完成后（特别是内容更新后），调用 JS 来渲染 Mermaid 图表
        if (_selectedReport != null)
        {
            await JSRuntime.InvokeVoidAsync("renderMermaid");
        }
    }

    private void ShowList()
    {
        _selectedReport = null;
        _htmlContent = "";
    }
}